import java.awt.*;
import java.awt.event.*;


import javax.swing.*;

import java.io.*;
import java.net.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

//For image
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class Client extends JFrame {
	
	private Socket clientSocket;
	private DataOutputStream outToServer;
	private JTextField ipField;


	public static void main(String s[]) {
		
		new Client();			
	}
	
	public Client(){
		
		createGUI();
		
		try {
			openSocket();
			
		} catch (Exception e) {
			
			//e.printStackTrace();			
			System.out.println("Socket opening prob");
		}			
	}
	
	
	public void createGUI(){
		
		JFrame frame = new JFrame("Falafel Super GUI");
		JPanel mainpanel = new JPanel();
		
		// Add a window listener for close button
		frame.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				
				try {
					clientSocket.close();
										
				} catch (IOException e1) {
					//e1.printStackTrace();
					System.out.println("closing socket prob");
				} finally {
					
					System.exit(0);
				}	
			}
		});
		
		
		//Contains component for ip connection
		JPanel IPpanel = new JPanel();
		
		Button button = new Button("Connect"); 
		button.addActionListener(new ButtonListener());
		button.setActionCommand("Submit button");
		
		JLabel jlbempty = new JLabel("Car IP Adress");
		jlbempty.setPreferredSize(new Dimension(100, 10));		
		
		ipField = new JTextField("IP Address", 30);
		ipField.setPreferredSize(new Dimension(10, 20));
		
		IPpanel.setLayout(new FlowLayout());
		IPpanel.add(jlbempty); 
		IPpanel.add(ipField);
		IPpanel.add(button);
		
		
		//reserved space for webcam images
		JPanel videoPanel = new ImagePanel();
		videoPanel.addMouseListener(new MouseEventList(mainpanel));
		videoPanel.setPreferredSize(new Dimension(100,350));
		
		
		//mainpanel will contain all the other panels
		mainpanel.setLayout(new BorderLayout());		
		mainpanel.add(IPpanel, BorderLayout.PAGE_START);
		mainpanel.add(videoPanel, BorderLayout.CENTER);

		
		//frame will contain only mainpanel
		frame.add(mainpanel);
		frame.pack();
		frame.setLocation(275, 250);
		frame.setVisible(true);
		
		
		
		//Add key listener to every component
		frame.getContentPane().addKeyListener(new KeyboardListener());
		mainpanel.addKeyListener(new KeyboardListener());
		IPpanel.addKeyListener(new KeyboardListener());
		ipField.addKeyListener(new KeyboardListener());
		button.addKeyListener(new KeyboardListener());
		jlbempty.addKeyListener(new KeyboardListener());
		videoPanel.addKeyListener(new KeyboardListener());
	}
	
	
	public void openSocket() throws Exception{

		clientSocket = new Socket("127.0.0.1", 5555);
		
		outToServer = new DataOutputStream(clientSocket.getOutputStream());
	}
	
	
	
    public void sendData(String Data) {
        
	    try {
	
            //System.out.println("Test");
        	outToServer.writeBytes(Data + "\n");
        	
        	
	    } catch (Exception e) {
	    
	    	System.out.println("Error sending data to socket");
	    }
    }	
    
    
	/*
	 * JPanel to show image
	 */
	public class ImagePanel extends JPanel{
		
		private BufferedImage image = null;
		private final int X_HALF_MARK = 258;
		private final int Y_HALF_MARK = 175;
    	
    	
	    public ImagePanel() {}

	    public void retrieveWebCamImage(){
	    	
	    	try {               
		    	   
	    		image = ImageIO.read(new File("images/arabFood.jpg"));
	          
	    	} catch (IOException e) {
	   
	    		System.out.println("Error in fetching the image");
	    	}	
	    }
	    
	    @Override
	    public void paintComponent(Graphics g) {
	    	
	    	//Call fct to retrieve img
	    	retrieveWebCamImage();
	    	
	    	if(image != null){
	    		
		    	int xHalfOfImage = image.getWidth()/2;
		    	int yHalfOfImage = image.getHeight()/2;    	
		    	
		    	int xCornerOfImg = X_HALF_MARK - xHalfOfImage;
		    	int yCornerOfImg = Y_HALF_MARK - yHalfOfImage;
		    	
		    	
		    	//If image is bigger then panel, then place it in the left upper corner of panel
		    	if(xCornerOfImg < 0)
		    		xCornerOfImg = 0;	    	
		    	if(yCornerOfImg < 0)
		    		yCornerOfImg = 0;
		    	
		    	
		    	g.drawImage(image, xCornerOfImg, yCornerOfImg, null);
		    	
	    	}	        
	    }	
	}
	
	
    public class MouseEventList implements MouseListener{
    	
    	private JPanel mainPanelCopy;
    	
    	
    	public MouseEventList(JPanel imgPanel){
    		
    		super();
    		
    		mainPanelCopy = imgPanel;
    	}
    	
		@Override
		public void mouseClicked(MouseEvent e) {
			
			mainPanelCopy.repaint();			
		}

		@Override
		public void mouseEntered(MouseEvent e) {}

		@Override
		public void mouseExited(MouseEvent e) {}

		@Override
		public void mousePressed(MouseEvent e) {}

		@Override
		public void mouseReleased(MouseEvent e) {}
    }
    
    
	public class KeyboardListener implements KeyListener{
		
		@Override
		public void keyPressed(KeyEvent e) {
			
			switch (e.getKeyCode()){
			
			case KeyEvent.VK_UP:
                sendData("FORWARD");
				System.out.println("Foward");
				break;
			
			case KeyEvent.VK_DOWN:
				System.out.println("Backwards");
                sendData("BACK");                				
                break;
			
			case KeyEvent.VK_LEFT:
				System.out.println("Left");
				
                sendData("LEFT");                				
                break;
			
			case KeyEvent.VK_RIGHT:				
				System.out.println("Right");
                sendData("RIGHT");                				
				break;
			}
		}

		
		@Override
		public void keyReleased(KeyEvent e) {}

		@Override
		public void keyTyped(KeyEvent e) {}		
	}
	
	public class ButtonListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			
			
			if(e.getActionCommand().equalsIgnoreCase("Submit button")){
				
				
				try {
			
					outToServer.writeBytes(ipField.getText() + "\n");
					System.out.println(ipField.getText());
					
				} catch (IOException e1) {
					
					//e1.printStackTrace();
					System.out.println("sending prob");
					
				} catch (NullPointerException e1) {
					
					//e1.printStackTrace();
					System.out.println("sending prob no connection, null pointer exception");
				}				
			}
		}
	}
}